/*
  广寒宫
  网址:www.guanghangong.xyz
 */
package com.moon.admin.sys.service;
import java.util.List;
import java.util.stream.Collectors;

import com.moon.admin.framework.MoonConstants;
import com.moon.admin.framework.cache.CacheService;
import com.moon.admin.framework.util.MoonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.sys.cache.UserCache;
import com.moon.admin.sys.domain.query.UserQuery;
import com.moon.admin.sys.entity.SysUserEntity;
import com.moon.admin.sys.entity.SysUserPostEntity;
import com.moon.admin.sys.entity.SysUserRoleEntity;
import com.moon.admin.sys.mapper.SysPostMapper;
import com.moon.admin.sys.mapper.SysUserMapper;
import com.moon.admin.sys.mapper.SysUserPostMapper;

/**
 * 员工管理
 * @author ninglong
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {

	@Autowired
	private SysUserPostMapper userPostMapper;
	@Autowired
	private SysPostMapper postMapper;
	@Autowired
	private CacheService cacheService;
	@Autowired
	private SysUserRoleService userRoleService;
	

	/**
	 * 可以根据部门id查询
	 */
	public IPage<SysUserEntity> selectListPage(UserQuery query){
		IPage<SysUserEntity> page = new Page<SysUserEntity>(query.getPage(),query.getLimit());
		List<SysUserEntity> list = this.baseMapper.getUserListPage(page,query);
		if(page.getTotal()==0) {
			return page;
		}
		for(SysUserEntity tmp:list){
			StringBuilder sb = new StringBuilder();
			List<SysUserPostEntity> tmpList = userPostMapper.getUserPostByUserId(tmp.getId());
			if(tmpList==null) {
				continue;
			}
			List<String> postIdDeptIds = Lists.newArrayList();
			for(SysUserPostEntity userPostEntity :tmpList){
				sb.append(userPostEntity.getDeptName()).append("/").append(userPostEntity.getPostName()).append("\n");
				if(MoonConstants.YesOrNoEnum.yes.ordinal()==userPostEntity.getPrimaryed()){
					tmp.setMainPostIdDeptId(userPostEntity.getPostId()+"_"+userPostEntity.getDeptId());
				}else{
					postIdDeptIds.add(userPostEntity.getPostId()+"_"+userPostEntity.getDeptId());
				}
			}
			tmp.setDeptPostName(sb.toString());
			tmp.setPostIdDeptIds(postIdDeptIds);
			List<Integer> roleIdList = userRoleService.list(Wrappers.<SysUserRoleEntity>lambdaQuery().eq(SysUserRoleEntity::getUserId, tmp.getId())).stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
			tmp.setRoleIds(roleIdList);
		}
		page.setRecords(list);
		return page;
	}
	
	/**
	 * 保存用户
	 */
	@Transactional(rollbackFor = MoonException.class)
	public void saveUser(SysUserEntity user){
		boolean isAdd = ToolUtils.isEmpty(user.getId());
		if(isAdd){
			this.save(user);
		}else{
			//删除旧的用户部门及岗位关系
			userPostMapper.delete(Wrappers.<SysUserPostEntity>lambdaQuery().eq(SysUserPostEntity::getUserId, user.getId()));
			//删除旧的用户角色关系
			userRoleService.remove(Wrappers.<SysUserRoleEntity>lambdaQuery().eq(SysUserRoleEntity::getUserId, user.getId()));
			this.updateById(user);
		}
		//添加新的员工部门及岗位关系
		String [] mainPostIdDeptIds = user.getMainPostIdDeptId().split("_");
		SysUserPostEntity userPost = SysUserPostEntity.builder().userId(user.getId()).postId(Integer.valueOf(mainPostIdDeptIds[0])).deptId(Integer.valueOf(mainPostIdDeptIds[1])).primaryed(MoonConstants.YesOrNoEnum.yes.ordinal()).build();
		userPostMapper.insert(userPost);
		//副岗位
		for(String postIdDeptId:user.getPostIdDeptIds()){
			String [] postIdDeptIds = postIdDeptId.split("_");
			userPost = SysUserPostEntity.builder().userId(user.getId()).postId(Integer.valueOf(postIdDeptIds[0])).deptId(Integer.valueOf(postIdDeptIds[1])).primaryed(MoonConstants.YesOrNoEnum.no.ordinal()).build();
			userPostMapper.insert(userPost);
		}
		List<SysUserRoleEntity> userRoleList = Lists.newArrayList();
		for(Integer roleId:user.getRoleIds()) {
			userRoleList.add(SysUserRoleEntity.builder().userId(user.getId()).roleId(roleId).build());
		}
		userRoleService.saveBatch(userRoleList);
		cacheService.del(UserCache.USER_BY_ID_CACHE+user.getId());
	}
}